/* eslint-disable no-undef */


// 121.36.62.77                                    111.229.88.119                               106.52.65.215
// ["0xffa4658ff14e486a3a57cc7163c153724c9d1904","0x350270a0400545ffc99ccfcf8b956294a2c98374","0xfe61d81503b8f660184076ca08a96381793d7718"]

// contract.methods
//   .winningProposal()
//   .call()
//   .then((result) => {
//     console.log(result);
//   });
module.exports = {
  deploy_first_voting: function (domain, voter_list, duration, init_vote_contract, bytecode,account) {
    return new Promise((resolve, reject) => {
      init_vote_contract
        .deploy({
          data: bytecode,
          arguments: [domain, voter_list, duration],
        })
        .send({
          from: account,
          gas: 3000000,
          gasPrice: "1",
        })
        .then(function (newContractInstance) {
          resolve(newContractInstance.options.address); // instance with the new contract address
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  vote: function (account, contract,domain, ip) {
    return new Promise((resolve, reject) => {
      contract.methods
        .vote(domain, ip)
        .send({ from: account, gas: 800000 },function(error, transactionHash){
          if(error){
            reject(error);
          }else{
            resolve(transactionHash);
          }
        })
    });
  },
  unlock: function (web3,account, password) {
    return new Promise((resolve, reject) => {
      web3.eth.personal
        .unlockAccount(account, password, 600)
        // 解锁成功
        .then(resolve("UNLOCK_SUCCESS"))
        .catch(reject("UNLOCK_FAILED"));
    });
  },
  getMostIp: function (contract) {
    return new Promise((resolve, reject) => {
      contract.methods
        .winningProposal()
        .call(function(error, result){
          if(error){
            reject(error)
          }else{
            resolve(result)
          }
        })
    });
  },
};
// function deploy_first_voting(domain, voter, duration, account, password) {
//   web3.eth.personal
//     .unlockAccount(account, password, 60)
//     .then(console.log("Account unlocked!"));
//   var myContract = new web3.eth.Contract(abi, {
//     from: account, // default from address
//     gasPrice: "1",
//   });
//   return new Promise((resolve, reject) => {
//     myContract
//       .deploy({
//         data: bytecode,
//         arguments: [domain, voter, duration],
//       })
//       .send({
//         from: account,
//         gas: 3000000,
//         gasPrice: "1",
//       })
//       .then(function (newContractInstance) {
//         resolve(newContractInstance.options.address); // instance with the new contract address
//       })
//       .catch((err) => {
//         reject(err);
//       });
//   });
// }
async function testDeply() {
  var account = config["account"];
  var password = config["password"];
  let [error1, res1] = await to(
    deploy_first_voting(
      "baidu.com",
      [
        "0xbc96126ca5ec498fc6f546fe4a3a4abf58dc044b",
        "0xb9cd3de25902ee3e1c700eb9f9b297e2424825f1",
        "0x2792ffc5562029b61338b195b2191fc9e3e85292",
      ],
      100,
      account,
      password
    )
  );
  if (error1) {
    console.log("合约部署出错");
    console.log(error1);
  } else {
    console.log("合约部署成功，地址如下:");
    console.log(res1);
  }
}
let unlock = function (account, password) {
  return new Promise((resolve, reject) => {
    web3.eth.personal
      .unlockAccount(account, password, 600)
      .then(resolve("Account unlocked!"))
      .catch(reject("Unlock failed"));
  });
};

let vote = function (domain, ip, account, contract) {
  return new Promise((resolve, reject) => {
    contract.methods
      .vote(domain, ip)
      .send({ from: account, gas: 800000 })
      .then((result) => resolve(result))
      .catch((err) => reject(err));
  });
};

async function testVote() {
  var account = "0xb9cd3de25902ee3e1c700eb9f9b297e2424825f1";
  var password = "123456";
  let [error1, res1] = await to(unlock(account, password));
  console.log(error1);
  if (error1) {
    await to(
      unlock(account, password)
    );
    console.log("尝试第二次解锁");
  }
  console.log(res1);
  let [error2, res2] = await to(
    vote("baidu.com", "2.2.2.2", account, contract)
  );
  if (error2) {
    console.log("投票过程发生错误，重新投票");
    console.log(error2);
  }
  console.log(res2);
}

// contract.events
//   .vote_event(
//     {
//       filter: {},
//       fromBlock: 2700,
//     },
//     function (error, event) {
//       console.log(error);
//     }
//   )
//   .on("data", function (event) {
//     // Fires on each incoming event with the event object as argument
//     console.log(
//       event.returnValues.vote +
//         "\t===>\t" +
//         event.returnValues.config +
//         "\t" +
//         "event.returnValues.status"
//     );
//   })
//   .on("changed", function (event) {
//     // Fires on each event which was removed from the blockchain.
//     console.log(event);
//   })
//   .on("error", function (error, receipt) {
//     // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
//     console.log(error);
//   });
// contract.methods
//   .winningProposal()
//   .call()
//   .then((result) => {
//     console.log(result);
//   });
// testDeply();
// 0xc102681075d898da08ff28bd3462371c47e6b2b7
// testVote()
